package com.power.sifa.std.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSON;
import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.ding.api.Di_userFeign;
import com.ding.dto.Di_userDto;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.utils.StringUtil;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.approve.model.Apl_target;
import com.power.sifa.std.dao.Std_admuserDao;
import com.power.sifa.std.model.Std_admuser;
import com.power.sifa.std.model.pageInfo.Std_admuserPageInfo;
import com.power.sifa.std.service.Std_admunitService;
import com.power.sifa.std.service.Std_admuserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 行政管理单位关联赣政通人员表业务层实现
 */
@Service
public class Std_admuserServiceImpl extends BaseServiceImpl implements Std_admuserService {

    @Autowired
    private Std_admuserDao dao;

    @Autowired
    private Di_userFeign diUserFeign;

    @Autowired
    private Std_admunitService stdAdmunitService;

    @Override
    public Std_admuser getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Std_admuser Std_admuser) {
        // save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (Std_admuser.getPrimaryKey() != null) {
            Std_admuser Std_admuserfDb = dao.findById(Std_admuser.getPrimaryKey()).orElse(null);
            if (Std_admuserfDb != null) {
                BeanUtils.copyProperties(Std_admuser, Std_admuserfDb);
                dao.save(Std_admuserfDb);
                return;
            }
        }
        dao.save(Std_admuser);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Std_admuser> findAll(Std_admuserPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if ("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        } else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() <= 1 ? 0 : pageInfo.getPageNumber() - 1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
    public List<Std_admuser> findAll() {
        return dao.findAll();
    }

    @Override
    public void saveAll(List<Std_admuser> list) {
        dao.saveAll(list);
    }

    @Override
    public void checkSave(Std_admuser stdAdmuser) {
        if(StrUtil.isEmpty(stdAdmuser.getId())){
            //新增
            addAdmuser(stdAdmuser);
        }else {
            //修改
            editAdmuser(stdAdmuser);
        }
    }

    private void addAdmuser(Std_admuser stdAdmuser) {
        //检验关联id
        if (!checkAdmunitid(stdAdmuser.getAdmunitid())) {
            throw new RuntimeException("关联的组织表id参数异常");
        }
        //检查这个号码是否合法
        if (!StringUtil.isEmpty(stdAdmuser.getMobile())) {
            if (this.dao.countByMobileAndAdmunit(stdAdmuser.getMobile()) != 0) {
                throw new RuntimeException("电话号码: " + stdAdmuser.getMobile() + ",用户已被绑定");
            }
        } else {
            throw new RuntimeException("电话参数异常");
        }
        Di_userDto userDto = getDiUserDto(stdAdmuser);
        if (null == userDto) {
            throw new RuntimeException("电话号码: " + stdAdmuser.getMobile() + ",不是合法用户");
        }
        //封装参数
        Std_admuser admuser = new Std_admuser();
        admuser.setId(NanoIdUtils.randomNanoId());
        admuser.setAdmunitid(stdAdmuser.getAdmunitid());
        admuser.setUserid(userDto.getId());
        admuser.setUsername(userDto.getUserName());
        admuser.setUnitid(userDto.getUnitId());
        admuser.setMobile(userDto.getMobile());
        admuser.setAddress(stdAdmuser.getAddress());
        this.dao.save(admuser);
    }

    private Di_userDto getDiUserDto(Std_admuser stdAdmuser) {
        List<String> list = new ArrayList<>(1);
        list.add(stdAdmuser.getMobile());
        ResponseDTO userResponseDTO = diUserFeign.getUserByPhones(list);
        if (0 != userResponseDTO.getCode()) {
            throw new RuntimeException("服务异常：" + userResponseDTO.getMsg());
        }
        List<Di_userDto> diUserList = JSONArray.parseArray(JSON.toJSONString(userResponseDTO.getData()), Di_userDto.class);
        if (ArrayUtil.isEmpty(diUserList)) {
            return null;
        } else {
            return diUserList.get(0);
        }
    }

    private Boolean checkAdmunitid(String admunitid) {
        // 如果admunitid为空或者根据admunitid查询到的admunit为null，则返回false
        return !StringUtil.isEmpty(admunitid) && stdAdmunitService.getById(admunitid) != null;
    }

    @Override
    public PageDataResponse listDetail(Std_admuserPageInfo pageInfo) {

        List<Map<String, Object>> dataList = this.dao.listDetail(pageInfo);
        // 分页
        PageDataResponse page = new PageDataResponse();
        if (CollectionUtil.isNotEmpty(dataList)) {
            Long total = Long.valueOf(pageInfo.getAllcount());
            int size = pageInfo.getPageSize() * pageInfo.getPageNumber();
            if (total.intValue() - size > 0) {
                page.setNextPage(pageInfo.getPageNumber() + 1);
            }
            page.setSize(pageInfo.getPageSize());
            page.setCurrent(pageInfo.getPageNumber());
            page.setTotal(total);
        } else {
            page.setSize(0);
            page.setCurrent(1);
            page.setTotal(0L);
        }
        page.setRecords(dataList);
        return page;
    }

    @Override
    public List<Std_admuser> queryByAdmId(String admId) {
        return this.dao.queryByAdmId(admId);
    }


    public void editAdmuser(Std_admuser admuser) {

        Std_admuser admuserDb = this.getById(admuser.getId());
        if (ObjectUtil.isEmpty(admuserDb)) {
            throw new RuntimeException("id参数异常，无法进行修改");
        }
        if(ObjectUtil.isEmpty(admuser.getAddress())){
            throw new RuntimeException("联系人地址参数异常");
        }
        if(admuser.getAdmunitid()!=null){
            if (!checkAdmunitid(admuser.getAdmunitid())) {
                throw new RuntimeException("组织机构表参数异常");
            }
        }else {
            admuser.setAdmunitid(admuserDb.getAdmunitid());
        }
        //检查这个号码是否合法
        if (!StrUtil.equals(admuserDb.getMobile(), admuser.getMobile())) {
            if (this.dao.countByMobileAndAdmunit(admuser.getMobile()) != 0) {
                throw new RuntimeException("电话号码: " + admuser.getMobile() + ",用户已被绑定");
            }
            Di_userDto diUserDto = getDiUserDto(admuser);
            if (null == diUserDto) {
                throw new RuntimeException("电话号码: " + admuser.getMobile() + ",不是合法用户");
            }
            admuser.setUserid(diUserDto.getId());
            admuser.setUsername(diUserDto.getUserName());
            admuser.setUnitid(diUserDto.getUnitId());
        } else {
            //设置成空就不会进行修改
            admuser.setMobile(admuserDb.getMobile());
            admuser.setUserid(admuserDb.getUserid());
            admuser.setUsername(admuserDb.getUsername());
            admuser.setUnitid(admuserDb.getUnitid());
        }
        this.dao.save(admuser);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTargetDiusers(List<Apl_target> targetList, List<Di_userDto> diUserList) {
        targetList = targetList.stream().filter(el -> StringUtils.isNotEmpty(el.getPhone())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(targetList) && CollUtil.isNotEmpty(diUserList)) {
            targetList.stream().forEach(target -> {
                String phone = target.getPhone();
                Di_userDto diUserDto = diUserList.stream().filter(el -> el.getMobile().equals(phone)).findFirst().orElse(null);
                if (ObjectUtil.isNotNull(diUserDto)) {
                    List<Std_admuser> admusers = dao.queryByAdmIdAndMobile(target.getAdmunitid(), phone);
                    if (CollUtil.isEmpty(admusers)) {
                        // 新增一条记录
                        //封装参数
                        Std_admuser admuser = new Std_admuser();
                        admuser.setId(NanoIdUtils.randomNanoId());
                        admuser.setAdmunitid(target.getAdmunitid());
                        admuser.setUserid(diUserDto.getId());
                        admuser.setUsername(target.getAgenter());
                        admuser.setUnitid(diUserDto.getUnitId());
                        admuser.setMobile(diUserDto.getMobile());
                        admuser.setAddress(target.getAddress());
                        this.dao.save(admuser);
                    }
                }
            });
        }
    }
}
